from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opinion_extractor.respondent.models import AbstractRespondent
from opinion_extractor.respondent.utils import get_respondent_model
from opinion_extractor.utils.models import create_dynamic_model, get_childs_own_fields
from base import OpinionBase


def _create_opinion_model():
    fields = {}
    answer_fields = []
    
    # Add answer[0..max_answers] fields - 1 answer per question
    max_answers = settings.OPINION_EXTRACTOR['max_questions_per_questionnaire']
    for x in xrange(max_answers):
        key = 'answer%d' % x
        fields[key] = models.PositiveIntegerField(
            _('answer to question #%d' % x),
            db_index=True,
            blank=True,
            null=True
        )
        answer_fields.append(key)
    
    # Add OPINION_EXTRACTOR['respondent_profile_model'] fields to this model
    respondent_model = get_respondent_model()
    respondent_meta = respondent_model._meta
    respondent_fields = get_childs_own_fields(
        respondent_model,
        AbstractRespondent
    )
    from copy import deepcopy
    for field_name in respondent_fields:
        fields[field_name] = deepcopy(respondent_meta.get_field(field_name))
    
    # Finaly create a Django model
    model = create_dynamic_model(
        'Opinion',
        base_class = OpinionBase,
        fields = fields,
        options = {
            'verbose_name': _('opinion'),
            'verbose_name_plural': _('opinions')
        },
        app_label = 'opinion',
        module = __name__
    )
    
    # Opinion model shouldn't change if all answers are the same
    model.changeable_fields = answer_fields
    
    # Add data in Meta which is used for validation
    model._meta.answer_fields = answer_fields
    model._meta.respondent_fields = respondent_fields
    
    return model


# TODO: Cache the created class
Opinion = _create_opinion_model()
